<template>
  <div class="database-manager page-container">
    <div class="page-header">
      <h2 class="page-title">数据库连接管理</h2>
      <a-button type="primary" @click="showAddForm = true">
        <template #icon><PlusOutlined /></template>
        添加新连接
      </a-button>
    </div>
    
    <!-- 数据库连接列表 -->
    <div class="connection-list">
      <a-row :gutter="16" class="connection-grid">
        <a-col :xs="24" :sm="12" :md="8" :lg="6" v-for="conn in connections" :key="conn?.id || index">
          <a-card class="connection-card" :data-id="conn?.id">
            <div class="connection-header" :class="{ 'connected': conn && conn.status === 'connected' }">
              <DatabaseOutlined :style="{ fontSize: '20px' }" />
              <span class="connection-name">{{ (conn && conn.name) || '未命名连接' }}</span>
            </div>
            <div class="connection-body">
              <div class="connection-info">
                <p><DatabaseOutlined /> {{ (conn && conn.host) || '未设置' }}</p>
                <p><FolderOutlined /> {{ (conn && conn.database) || '未设置' }}</p>
                <p><InfoCircleOutlined /> {{ (conn && conn.type) || '未设置' }}</p>
              </div>
              <div class="connection-status">
                <a-tooltip :title="(conn && conn.lastTested) ? `上次测试: ${conn.lastTested}` : '未测试'">
                  <a-tag :color="(conn && conn.status === 'connected') ? 'success' : (conn && conn.status === 'unknown') ? 'default' : 'error'">
                    {{ (conn && conn.status === 'connected') ? '已连接' : (conn && conn.status === 'unknown') ? '未知' : '未连接' }}
                  </a-tag>
                </a-tooltip>
              </div>
            </div>
            <div class="connection-footer">
              <a-space>
                <a-button type="text" @click="testConnection(conn)">
                  <template #icon><PlayCircleOutlined /></template>
                </a-button>
                <a-button type="text" @click="viewDetails(conn)">
                  <template #icon><EyeOutlined /></template>
                </a-button>
                <a-button type="text" danger @click="deleteConnection(conn)">
                  <template #icon><DeleteOutlined /></template>
                </a-button>
              </a-space>
            </div>
          </a-card>
        </a-col>
      </a-row>
    </div>

    <!-- 添加新连接表单 -->
    <a-modal
      v-model:open="showAddForm"
      title="添加新连接"
      :width="600"
      @ok="createConnection"
      @cancel="showAddForm = false"
    >
      <a-form
        ref="connectionForm"
        :model="newConnection"
        :rules="rules"
        :label-col="{ span: 6 }"
        :wrapper-col="{ span: 18 }"
      >
        <a-form-item label="连接名称" name="name">
          <a-input v-model:value="newConnection.name" placeholder="请输入连接名称" />
        </a-form-item>
        <a-form-item label="数据库类型" name="type">
          <a-select v-model:value="newConnection.type" placeholder="请选择数据库类型">
            <a-select-option value="mysql">MySQL</a-select-option>
            <a-select-option value="postgresql">PostgreSQL</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="主机地址" name="host">
          <a-input v-model:value="newConnection.host" placeholder="例如：localhost 或 IP地址" />
        </a-form-item>
        <a-form-item label="端口" name="port">
          <a-input-number v-model:value="newConnection.port" :min="1" :max="65535" style="width: 100%" />
        </a-form-item>
        <a-form-item label="数据库名" name="database">
          <a-input v-model:value="newConnection.database" placeholder="请输入数据库名" />
        </a-form-item>
        <a-form-item label="用户名" name="username">
          <a-input v-model:value="newConnection.username" placeholder="请输入数据库用户名" />
        </a-form-item>
        <a-form-item label="密码" name="password">
          <a-input-password v-model:value="newConnection.password" placeholder="请输入数据库密码" />
        </a-form-item>
      </a-form>
    </a-modal>

    <!-- 连接详情对话框 -->
    <a-modal
      v-model:open="detailsVisible"
      title="连接详情"
      :width="800"
      @cancel="detailsVisible = false"
    >
      <template v-if="selectedConnection">
        <a-descriptions bordered :column="2">
          <a-descriptions-item label="连接名称">{{ selectedConnection.name }}</a-descriptions-item>
          <a-descriptions-item label="数据库类型">{{ selectedConnection.type }}</a-descriptions-item>
          <a-descriptions-item label="主机地址">{{ selectedConnection.host }}</a-descriptions-item>
          <a-descriptions-item label="端口">{{ selectedConnection.port }}</a-descriptions-item>
          <a-descriptions-item label="数据库名">{{ selectedConnection.database }}</a-descriptions-item>
          <a-descriptions-item label="用户名">{{ selectedConnection.username }}</a-descriptions-item>
          <a-descriptions-item label="连接状态">
            <a-tag :color="selectedConnection.status === 'connected' ? 'success' : 'error'">
              {{ selectedConnection.status === 'connected' ? '已连接' : '未连接' }}
            </a-tag>
          </a-descriptions-item>
          <a-descriptions-item label="最后测试时间">
            {{ selectedConnection.lastTested || '未测试' }}
          </a-descriptions-item>
        </a-descriptions>
        <div class="connection-stats" v-if="selectedConnection.stats">
          <h4>连接统计</h4>
          <a-row :gutter="16">
            <a-col :span="8">
              <a-statistic title="活跃查询数" :value="selectedConnection.stats.activeQueries || 0" />
            </a-col>
            <a-col :span="8">
              <a-statistic title="连接时长" :value="selectedConnection.stats.uptime || '0分钟'" />
            </a-col>
            <a-col :span="8">
              <a-statistic title="查询总数" :value="selectedConnection.stats.totalQueries || 0" />
            </a-col>
          </a-row>
        </div>
      </template>
    </a-modal>

    <!-- 连接测试结果弹窗 -->
    <a-modal
      v-model:open="testResultVisible"
      title="连接测试结果"
      :width="500"
      @cancel="testResultVisible = false"
    >
      <div class="test-result">
        <a-result
          :status="testResult.success ? 'success' : 'error'"
          :title="testResult.success ? '连接成功' : '连接失败'"
          :sub-title="testResult.message"
        >
          <template #extra>
            <div class="test-details" v-if="testResult.details">
              <a-descriptions bordered :column="1">
                <a-descriptions-item v-if="testResult.details.version" label="数据库版本">
                  {{ testResult.details.version }}
                </a-descriptions-item>
                <a-descriptions-item v-if="testResult.details.charset" label="字符集">
                  {{ testResult.details.charset }}
                </a-descriptions-item>
                <a-descriptions-item v-if="testResult.details.timezone" label="时区">
                  {{ testResult.details.timezone }}
                </a-descriptions-item>
                <a-descriptions-item v-if="testResult.details.error" label="错误详情" class="error-details">
                  {{ testResult.details.error }}
                </a-descriptions-item>
              </a-descriptions>
            </div>
          </template>
        </a-result>
      </div>
    </a-modal>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import { message, Modal } from 'ant-design-vue'
import { useDatabaseStore } from '../stores/database'
import {
  PlusOutlined,
  DatabaseOutlined,
  FolderOutlined,
  InfoCircleOutlined,
  PlayCircleOutlined,
  EyeOutlined,
  DeleteOutlined
} from '@ant-design/icons-vue'

// 初始化数据库存储
const databaseStore = useDatabaseStore()

// 状态变量
const connections = ref([])
const connectionForm = ref(null)
const loading = ref(false)
const refreshInterval = ref(null)
const newConnection = ref({
  name: '',
  type: 'mysql',
  host: '',
  port: 3306,
  database: '',
  username: '',
  password: ''
})
const testResultVisible = ref(false)
const testResult = ref({ success: false, message: '' })
const detailsVisible = ref(false)
const selectedConnection = ref(null)
const showAddForm = ref(false)

// 表单验证规则
const rules = {
  name: [{ required: true, message: '请输入连接名称', trigger: 'blur' }],
  type: [{ required: true, message: '请选择数据库类型', trigger: 'change' }],
  host: [{ required: true, message: '请输入主机地址', trigger: 'blur' }],
  port: [{ required: true, message: '请输入端口号', trigger: 'change' }],
  database: [{ required: true, message: '请输入数据库名', trigger: 'blur' }],
  username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }]
}

// 获取连接列表
const fetchConnections = async () => {
  try {
    const { data } = await databaseStore.fetchConnections()
    connections.value = data
  } catch (error) {
    message.error('获取连接列表失败：' + error.message)
  }
}

// 测试连接
const testConnection = async (connection) => {
  try {
    const result = await databaseStore.testConnection(connection.id)
    testResult.value = {
      success: result.success,
      message: result.message,
      details: result.details
    }
    testResultVisible.value = true
  } catch (error) {
    message.error('测试连接失败：' + error.message)
  }
}

// 创建新连接
const createConnection = async () => {
  try {
    await connectionForm.value.validate()
    await databaseStore.createConnection(newConnection.value)
    message.success('连接创建成功')
    showAddForm.value = false
    await fetchConnections()
    // 重置表单
    connectionForm.value.resetFields()
  } catch (error) {
    message.error('创建连接失败：' + error.message)
  }
}

// 更新连接
const updateConnection = async (conn) => {
  try {
    await databaseStore.updateConnection(conn)
    message.success('更新连接成功')
    showAddForm.value = false
    await fetchConnections()
  } catch (error) {
    message.error('更新连接失败：' + error.message)
  }
}

// 删除连接
const deleteConnection = async (connection) => {
  Modal.confirm({
    title: '确认删除',
    content: `确定要删除连接 "${connection.name}" 吗？`,
    okText: '确认',
    cancelText: '取消',
    async onOk() {
      try {
        await databaseStore.deleteConnection(connection.id)
        message.success('删除连接成功')
        await fetchConnections()
      } catch (error) {
        message.error('删除连接失败：' + error.message)
      }
    }
  })
}

// 查看连接详情
const viewDetails = async (connection) => {
  try {
    const connectionDetails = await databaseStore.getConnection(connection.id)
    selectedConnection.value = connectionDetails
    detailsVisible.value = true
  } catch (error) {
    message.error('获取连接详情失败：' + error.message)
  }
}

// 重置表单
const resetForm = () => {
  if (connectionForm.value) {
    connectionForm.value.resetFields()
    newConnection.value = {
      name: '',
      type: 'mysql',
      host: '',
      port: 3306,
      database: '',
      username: '',
      password: ''
    }
  }
}

// 启动自动刷新
const startAutoRefresh = () => {
  stopAutoRefresh()
  refreshInterval.value = setInterval(async () => {
    if (!loading.value) {
      await fetchConnections()
    }
  }, 30000)
}

// 停止自动刷新
const stopAutoRefresh = () => {
  if (refreshInterval.value) {
    clearInterval(refreshInterval.value)
    refreshInterval.value = null
  }
}

onMounted(async () => {
  await fetchConnections()
  // 定时刷新连接状态，每60秒刷新一次
  refreshInterval.value = setInterval(async () => {
    await fetchConnections()
  }, 60000)
})

onUnmounted(() => {
  if (refreshInterval.value) {
    clearInterval(refreshInterval.value)
  }
})
</script>

<style scoped>
.database-manager {
  padding: 24px;
  max-width: 1440px;
  margin: 0 auto;
  min-height: 100vh;
}

.page-header {
  margin-bottom: 24px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 16px 24px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.03);
}

.page-title {
  font-size: 24px;
  font-weight: 600;
  margin: 0;
  color: rgba(0, 0, 0, 0.85);
}

.connection-list {
  margin-top: 24px;
}

.connection-card {
  border-radius: 8px;
  overflow: hidden;
  transition: all 0.3s;
  height: 100%;
}

.connection-card:hover {
  transform: translateY(-4px);
}

.connection-header {
  padding: 16px;
  background-color: #fafafa;
  display: flex;
  align-items: center;
  gap: 8px;
  border-bottom: 1px solid #f0f0f0;
}

.connection-header.connected {
  background: #f6ffed;
  color: #52c41a;
}

.connection-name {
  font-size: 16px;
  font-weight: 500;
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.connection-body {
  padding: 16px;
}

.connection-info p {
  margin: 8px 0;
  display: flex;
  align-items: center;
  gap: 8px;
  color: rgba(0, 0, 0, 0.65);
  padding: 8px 16px;
  border-radius: 4px;
  background-color: #fafafa;
  transition: all 0.3s;
}

.connection-info p:hover {
  background-color: #f5f5f5;
  transform: translateX(4px);
}

.connection-status {
  display: flex;
  justify-content: flex-end;
  margin-top: 16px;
}

.connection-footer {
  padding: 8px 16px;
  background-color: #fafafa;
  display: flex;
  justify-content: flex-end;
  border-top: 1px solid #f0f0f0;
}

.connection-stats {
  margin-top: 24px;
}

.connection-stats h4 {
  margin-bottom: 16px;
  color: rgba(0, 0, 0, 0.85);
  font-weight: 500;
}

.test-details {
  margin-top: 24px;
}

.error-details {
  color: #ff4d4f;
}

@media (max-width: 768px) {
  .database-manager {
    padding: 16px;
  }

  .page-header {
    padding: 12px 16px;
    flex-direction: column;
    gap: 12px;
    align-items: stretch;
  }

  .page-title {
    font-size: 20px;
    text-align: center;
  }
}
</style>